<template>
    <div class="table-page">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="基础设置" name="first">
                <div class="form-page">
                    <el-form
                        ref="dataForm"
                        :model="dataForm"
                        label-width="8em"
                        :rules="dataFormRule"
                        class="data-form"
                    >
                        <div class="form-item">
                            <div class="yx-start al-start data">
                                <el-form-item label="套餐名称" prop="name">
                                    <el-input v-model="dataForm.name"></el-input>
                                </el-form-item>
                                <el-form-item
                                    label="行业"
                                    prop="industryId"
                                >
                                    <el-select
                                        v-model="dataForm.industryId"
                                        placeholder="请选择行业"
                                    >
                                        <el-option
                                            v-for="item in industryData"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item
                                    label="考试"
                                    prop="examId"
                                >
                                    <el-select
                                        v-model="dataForm.examId"
                                        placeholder="请选择考试"
                                        reserve-keyword
                                        filterable
                                    >
                                        <el-option
                                            v-for="item in examData"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="排序" prop="sort">
                                    <el-input v-model="dataForm.sort"></el-input>
                                </el-form-item>
                                <el-form-item label="原价(元)" prop="price">
                                    <el-input-number v-model="dataForm.price" :min="0"></el-input-number>
                                </el-form-item>
                                <el-form-item label="折扣价(元)" prop="discountPrice">
                                    <el-input-number v-model="dataForm.discountPrice" :min="0"></el-input-number>
                                </el-form-item>
                                <el-form-item label="天猫价(元)" prop="tmPrice">
                                    <el-input-number v-model="dataForm.tmPrice" :min="0"></el-input-number>
                                </el-form-item>
                                <el-form-item label="代理价(元)" prop="agentPrice">
                                    <el-input-number v-model="dataForm.agentPrice" :min="0"></el-input-number>
                                </el-form-item>
                                <el-form-item
                                    label="有效日期"
                                    prop="endDate"
                                >
                                    <el-date-picker
                                        v-model="dataForm.endDate"
                                        type="date"
                                        placeholder="选择日期"
                                        value-format="yyyy-MM-dd"
                                        :picker-options="datePickOption"
                                        style="width: 100%;"
                                    ></el-date-picker>
                                </el-form-item>
                                <el-form-item
                                    label="有效天数"
                                    prop="days"
                                >
                                    <el-input-number
                                        v-model="dataForm.days"
                                        :min="0"
                                    ></el-input-number>
                                </el-form-item>

                            </div>
                            <el-form-item label="标签" prop="tagIds">
                                <el-checkbox-group v-if="queryId===undefined||tagList!==undefined && dataForm.id"
                                                   v-model="dataForm.tagIds"
                                                   size="medium">
                                    <el-checkbox v-for="item in tagList" :key="item.id" :label="item.id" border>
                                        {{ item.name }}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                            <el-form-item
                                v-if="queryId===undefined||queryId!==undefined && dataForm.id"
                                label="描述"
                                prop="remark"
                                style=" width: 1200px"
                            >
                                <tinymce
                                    v-if="showTinymce"
                                    v-model="dataForm.remark"
                                />
                            </el-form-item>
                            <el-form-item
                                label="封面"
                                prop="cover"
                                style=" width: 1200px"
                            >
                                <el-upload
                                    :limit="1"
                                    class="avatar-uploader"
                                    action="https://jsonplaceholder.typicode.com/posts/"
                                    :show-file-list="false"
                                    :on-progress="handleProgress"
                                    :http-request="customUpload"
                                    accept=".jpg,.jpeg,image/jpeg"
                                >
                                    <img v-if="dataForm.coverUrl" :src="dataForm.coverUrl" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                                <el-popover
                                    placement="top"
                                    width="200"
                                    trigger="click"
                                    title="注意"
                                    content="上传的png图片，无法预览，所以上传jpg图片"
                                >
                                    <el-button slot="reference" style="color: blue">注：宽高比为700px / 900px</el-button>
                                </el-popover>
                            </el-form-item>
                            <el-form-item
                                label="长图"
                                prop="introduce"
                                style=" width: 1200px"
                            >
                                <img v-for="(item,index) in dataForm.introduce" :key="index" :src="item"  class="avatar"/>
                                <el-upload

                                    class="avatar-uploader"
                                    action="#"
                                    :show-file-list="false"
                                    :on-progress="handleProgress"
                                    :http-request="customUpload1"
                                    accept=".jpg,.jpeg,image/jpeg"
                                >
                                    <i class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                                <span style="color: blue">注：长图上传jpg，统一宽高比为800px / 1000px</span>
                            </el-form-item>
                        </div>
                    </el-form>

                    <span>
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="toSku"
                >下一步</el-button
                >
            </span>
                </div>
            </el-tab-pane>
            <el-tab-pane label="sku设置" name="second">
                <el-form
                    ref="skuForm"
                    :model="skuForm"
                    label-width="6em"
                    :rules="skuFormRule"
                    class="table-edit-from"
                    @submit.native.stop.prevent
                >
                    <el-form-item label="搜索">
                        <el-input v-model="searchSkuName"
                                  style="margin-left: 3em"
                                  placeholder="请输入sku属性"
                                  @change="searchSkuAttr"></el-input>
                        <el-button @click="all">全选</el-button>
                    </el-form-item>
                    <el-form-item label="sku属性:" prop="name">
                        <div v-for="(item, idx) in tempSkuForm.skuList" :key="idx">
                            <el-form-item :label="item.name + ':' " style="margin-top: 10px">

                                <el-checkbox-group
                                    v-model="item.checkIds"
                                    size="medium"
                                >
                                    <el-checkbox v-for="action in item.children" :key="action.id" :label="action.id"
                                                 border>
                                        {{ action.name }}
                                    </el-checkbox>

                                    <el-input v-model="item.expand"
                                              style="margin-left: 3em"
                                              placeholder="请输入sku属性"
                                              @keyup.enter.native="addSkuAttr(item)"></el-input>
                                    <!--                                    <el-input style="margin-left: 3em;" size="small" v-if="item.id!='guige'" v-model="item.exter" placeholder="请输入内容"  />-->
                                </el-checkbox-group>

                            </el-form-item>

                        </div>
                    </el-form-item>
                    <!--                    <el-form-item label="科目:" prop="categoryIds">-->
                    <!--                        <el-cascader-->
                    <!--                            v-model="skuForm.categoryIds"-->
                    <!--                            :options="categoryData"-->
                    <!--                            :props="categoryProps"-->
                    <!--                            clearable></el-cascader>-->
                    <!--                    </el-form-item>-->

                </el-form>
                <span>


                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="() =>{activeName ='first'}"
                >上一步</el-button
                >
                    <el-button
                        :loading="submitFlag"
                        type="primary"
                        @click="createSku"
                    >生成sku并下一步</el-button
                    >
                    <el-button
                        :loading="submitFlag"
                        type="primary"
                        @click="() =>{activeName ='third'}"
                    >下一步</el-button
                    >
            </span>
            </el-tab-pane>
            <el-tab-pane label="sku列表" name="third">
                <h3>老数据</h3>
                <div class="table-page">

                    <div class="table-data-box ">
                        <el-table
                            ref="table"
                            v-loading="tableLoading"
                            :data="oldTableDate"
                            border
                            style="width: 100%;min-height:20em"
                            row-key="id"
                            @selection-change="tableSelectionChange"
                        >
                            <el-table-column type="selection" width="55" align="center">
                            </el-table-column>
                            <el-table-column
                                type="index"
                                label="序号"
                                width="50">
                            </el-table-column>
                            <el-table-column
                                prop="name"
                                label="名称"
                                min-width="100"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.name"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="price"
                                label="价格(元)"
                                width="80"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.price"
                                              @blur="changePrice('price',scope.row)"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="discountPrice"
                                label="折扣价(元)"
                                width="80"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.discountPrice"
                                              @blur="changePrice('discountPrice',scope.row)"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="tmPrice"
                                label="天猫价(元)"
                                width="80"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.tmPrice"
                                              @blur="changePrice('tmPrice',scope.row)"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="agentPrice"
                                label="代理价(元)"
                                width="80"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.agentPrice"
                                              @blur="changePrice('agentPrice',scope.row)"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="categoryIds"
                                label="科目"
                                min-width="120"
                            >
                                <template slot-scope="scope">
                                    <el-cascader
                                        v-model="scope.row.categoryIds"
                                        :options="categoryData"
                                        :props="categoryProps"
                                        size="small"
                                        clearable
                                        @change="getProductData(scope.row)"
                                    ></el-cascader>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="productIds"
                                label="产品"
                                min-width="120"
                            >
                                <template slot-scope="scope">
                                    <el-cascader
                                        v-model="scope.row.productIds"
                                        :options="scope.row.productList"
                                        :props="productProps"
                                        size="small"
                                        clearable></el-cascader>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="skuAttrNameList"
                                label="sku属性"
                                min-width="180"
                            >
                                <template slot-scope="scope">
                                    <el-tag v-for="(item,index) in scope.row.skuAttrNameList" :key="index"> {{
                                            item
                                        }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="sort"
                                label="排序"
                                width="100"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.sort"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="enable"
                                label="状态"
                                min-width="60"
                                align="center"
                            >
                                <template slot-scope="scope">
                                    <k-tag
                                        :tag="scope.row.enable ? { desc:'已上架',color:'#6ADA8D'} : { desc:'已下架',color:'#fb4e4e'}"></k-tag>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="操作"
                                width="200"
                                align="center"
                                fixed="right"
                            >
                                <template slot-scope="scope">

                                    <el-button
                                        v-if="!scope.row.edit"
                                        class="warning"
                                        type="text"
                                        icon="el-icon-delete"
                                        size="mini"
                                        :loading="scope.row.opLoading"
                                        @click="removeSkuTable(tableData,scope.$index)"
                                    >移除
                                    </el-button>
                                    <el-button
                                        v-if="scope.row.enable"
                                        :loading="scope.row.opLoading"
                                        type="text"
                                        size="mini"
                                        class="warning"
                                        icon="el-icon-lock"
                                        @click="() =>scope.row.enable = false"
                                    >下架
                                    </el-button>
                                    <el-button
                                        v-if="!scope.row.enable"
                                        :loading="scope.row.opLoading"
                                        size="mini"
                                        type="text"
                                        icon="el-icon-unlock"
                                        @click="() =>scope.row.enable = true"
                                    >上架
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination
                            style="margin-top: 2em;text-align: right"
                            layout="prev, pager, next"
                            background
                            :page-size="pageSize"
                            :total="total"
                            @current-change="handleCurrentChange"
                        >
                        </el-pagination>
                    </div>
                </div>
                <h3>新数据</h3>
                <div class="table-page">

                    <div class="table-data-box">
                        <el-table
                            ref="table"
                            v-loading="skuTableLoading"
                            :data="newSkuTable"
                            border
                            style="width: 100%;min-height:20em"
                            row-key="id"
                            @selection-change="tableSelectionChange"
                        >
                            <el-table-column type="selection" width="55" align="center">
                            </el-table-column>
                            <el-table-column
                                type="index"
                                label="序号"
                                width="50">
                            </el-table-column>
                            <el-table-column
                                prop="name"
                                label="名称"
                                min-width="100"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.name"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="price"
                                label="价格(元)"
                                width="80"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.price"
                                              @blur="newChangePrice('price',scope.row)"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="discountPrice"
                                label="折扣价(元)"
                                width="80"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.discountPrice"
                                              @blur="newChangePrice('discountPrice',scope.row)"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="tmPrice"
                                label="天猫价(元)"
                                width="80"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.tmPrice"
                                              @blur="newChangePrice('tmPrice',scope.row)"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="agentPrice"
                                label="代理价(元)"
                                width="80"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.agentPrice"
                                              @blur="newChangePrice('agentPrice',scope.row)"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="categoryIds"
                                label="科目"
                                min-width="120"
                            >
                                <template slot-scope="scope">
                                    <el-cascader
                                        v-model="scope.row.categoryIds"
                                        :options="categoryData"
                                        :props="categoryProps"
                                        size="small"
                                        clearable
                                        @change="getProductData(scope.row)"
                                    ></el-cascader>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="productIds"
                                label="产品"
                                min-width="120"
                            >
                                <template slot-scope="scope">
                                    <el-cascader
                                        v-model="scope.row.productIds"
                                        :options="scope.row.productList"
                                        :props="productProps"
                                        size="small"
                                        clearable></el-cascader>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="skuAttrNameList"
                                label="sku属性"
                                min-width="180"
                            >
                                <template slot-scope="scope">
                                    <el-tag v-for="(item,index) in scope.row.skuAttrNameList" :key="index"> {{
                                            item
                                        }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="sort"
                                label="排序"
                                width="100"
                            >
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.sort"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="enable"
                                label="状态"
                                min-width="60"
                                align="center"
                            >
                                <template slot-scope="scope">
                                    <k-tag
                                        :tag="scope.row.enable ? { desc:'已上架',color:'#6ADA8D'} : { desc:'已下架',color:'#fb4e4e'}"></k-tag>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="操作"
                                width="200"
                                align="center"
                                fixed="right"
                            >
                                <template slot-scope="scope">

                                    <el-button
                                        v-if="!scope.row.edit"
                                        class="warning"
                                        type="text"
                                        icon="el-icon-delete"
                                        size="mini"
                                        :loading="scope.row.opLoading"
                                        @click="removeSkuTable(newSkuTable,scope.$index)"
                                    >移除
                                    </el-button>
                                    <el-button
                                        v-if="scope.row.enable"
                                        :loading="scope.row.opLoading"
                                        type="text"
                                        size="mini"
                                        class="warning"
                                        icon="el-icon-lock"
                                        @click="() =>scope.row.enable = false"
                                    >下架
                                    </el-button>
                                    <el-button
                                        v-if="!scope.row.enable"
                                        :loading="scope.row.opLoading"
                                        size="mini"
                                        type="text"
                                        icon="el-icon-unlock"
                                        @click="() =>scope.row.enable = true"
                                    >上架
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
                <span>
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="save"
                >保存
                </el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="() =>{activeName ='second'}"
                >上一步
                </el-button
                >
                </span>
            </el-tab-pane>

        </el-tabs>

    </div>
</template>

<script>
import Fetch from "@/api/request.js";
import {FormPage, TablePage} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import {get, put, post} from "@/api/request";
import {beanCopy, treeList2Tree} from "@/utils";
import Tinymce from "@/components/Tinymce";
import tmpList from "@/views/models/tmp-list";
import {ossUpload} from "@/utils/oss";

export default {
    name: "PackageAdd",
    components: {Tinymce},
    mixins: [TablePage, FormPage],
    data() {
        return {
            datePickOption: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
                }
            },
            total: 0,
            currentPage: 1,
            pageSize: 15,
            searchSkuName: "",
            firstupdateSkuAttr: true,
            canSave: true,
            updateExamFirst: true,
            loadSkuListFirst: true,
            showTinymce: true,
            categoryProps: {
                multiple: true,
                checkStrictly: true,
                emitPath: false,
                label: "name",
                value: "id",
            },
            productProps: {
                multiple: true,
                checkStrictly: true,
                emitPath: false,
                label: "name",
                value: "id",
            },
            activeName: "first",
            industryData: [],
            categoryData: [],
            categoryMap: {},
            productData: [],
            productMap: {},
            skuAttrMap: {},
            baseCategoryIds: [],
            categoryFlag: false,
            examData: [],
            tagList: [],
            skuAttrList: [],
            skuForm: {
                skuList: [],
                categoryIds: [],
                skuAttrList: [],
            },
            tempSkuForm: {
                skuList: [],
                categoryIds: [],
                skuAttrList: [],

            },
            newSkuTable: [],
            skuTableLoading: false,
            oldSkuTable: [],
            skuFormRule: {},
            dataForm: {
                id: null,
                name: null,
                price: 0,
                discountPrice: 0,
                tmPrice: 0,
                agentPrice: 0,
                sort: 100,
                industryId: null,
                examId: null,
                tagIds: [],
                skuIds: [],
                days: null,
                endDate: null,
                examType: "zhiye",
                skuAttrs: {},
                coverUrl: "",
                introduce: []
            },
            initAddForm: {
                id: null,
                name: null,
                price: 0,
                discountPrice: 0,
                tmPrice: 0,
                agentPrice: 0,
                sort: 100,
                industryId: null,
                examId: null,
                tagIds: [],
                skuIds: [],
                days: null,
                endDate: null,
                examType: "zhiye",
                skuAttrs: {},
                coverUrl: "",
                introduce: []
            },
            dataFormRule: {
                industryId: [
                    {
                        required: true,
                        message: "请选择行业",
                        trigger: "blur"
                    }
                ],

                examId: [
                    {
                        required: true,
                        message: "请选择考试",
                        trigger: "blur"
                    }
                ],
                name: [
                    {
                        required: true,
                        message: "请输入套餐名称",
                        trigger: "blur"
                    }
                ],
                price: [
                    {
                        required: true,
                        message: "请输入产品价格",
                        trigger: "blur"
                    }
                ],
                discountPrice: [
                    {
                        required: true,
                        message: "请输入折扣价格",
                        trigger: "blur"
                    }
                ],
                tmPrice: [
                    {
                        required: true,
                        message: "请输入天猫价格",
                        trigger: "blur"
                    }
                ],
                agentPrice: [
                    {
                        required: true,
                        message: "请输入产品价格",
                        trigger: "blur"
                    }
                ],
            },
            skuObj: {
                id: null,
                industryId: null,
                examId: null,
                categoryIds: [],
                productIds: [],
                productList: [],
                price: 0,
                discountPrice: 0,
                agentPrice: 0,
                tmPrice: 0,
                name: null,
                packageId: null,
                skuAttrIds: [],
                enable: true,
                remark: null,
                skuAttrNameList: [],
                sort: 100
            },

        };
    },
    computed: {
        ...mapState({
            productCodeStatus: state => state.status.productCodeStatus,
        }),
        oldTableDate() {
            return this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
    },
    watch: {
        "dataForm.industryId"(industryId) {
            if (this.dataForm.addAction) {
                this.dataForm.examId = null;
            } else if (!this.updateExamFirst) {
                this.dataForm.examId = null;
            }
            this.updateExamFirst = false;
            if (industryId) {
                this.loadExam(industryId);
            } else {
                this.examData = [];
            }
        },
        "dataForm.examId"(examId) {
            this.loadSku(examId);
            if (examId) {
                this.loadCategory(examId);
                this.loadProduct(examId);
                this.loadTags(examId);
            } else {
                this.categoryMap = {},
                    this.baseCategoryIds = [];
                this.categoryData = [];
                this.productData = [];
            }

        },
    },
    activated() {
        this.showTinymce = true;
    },
    deactivated() {
        this.showTinymce = false;
    },
    created() {
        this.loadInitData();
    },

    methods: {
        handleProgress(event, file, fileList) {
            // event 包含进度信息
            console.log("上传进度：", event.percent);
        },
        // 上传到oss
        customUpload(options) {
            // 显示上传进度提示
            const loading = this.$loading({
                lock: true,
                text: "上传中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            });
            let url=null;
            ossUpload("cdn", options.file.name, options.file, (process) => {
                // options.onProgress({
                //         percent: process*100,
                //         loaded: process*100,
                //         total:100
                // })
                loading.text = "上传中..." + Math.floor(process * 100) + "%";
                // console.log('=======' + process)
            }, (client) => {
                // url = this.$store.state.systemImageConfig[0].imagesHost + client.options.path
                // url = client.options.path
                url = this.$store.state.systemImageConfig[0].imagesHost + client.options.path
            }).then(() => {
                this.dataForm.coverUrl =url
                this.$message({message: "上传成功", type: "success"})

            }).catch(() => {
                this.$message({message: "上传失败", type: "error"})


            }).finally((e) => {
                loading.close();
            })

        },
        customUpload1( options){
            const loading = this.$loading({
                lock: true,
                text: "上传中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            });
            let url=null;
           ossUpload("cdn", options.file.name, options.file, (process) => {
               loading.text = "上传中..." + Math.floor(process * 100) + "%";
            }, (client) => {
                url = this.$store.state.systemImageConfig[0].imagesHost + client.options.path

            }).then(() => {
                this.dataForm.introduce.push( url)
            }).catch(_ => {
                this.$message.error("上传失败!");
                console.log("111111111111",_)
                debugger
            })  .finally((e) => {
               loading.close();
           })
        },
        loadInitData() {
            this.queryId = this.$route.query.id;
            if (this.queryId) {
                this.addAction = false;
                this.loadDataFlag = true;
            }
            this.loadOldData(this.queryId);
            this.loadIndustry();
            this.loadTags();
            this.loadSku();
        },
        searchSkuAttr(data) {
            for (let i = 0; i < this.tempSkuForm.skuList.length; i++) {
                this.skuForm.skuList[i].checkIds = this.tempSkuForm.skuList[i].checkIds
            }
            let stringify = JSON.stringify(this.skuForm.skuList);
            this.tempSkuForm.skuList = JSON.parse(stringify);
            if (this.searchSkuName !== null && this.searchSkuName !== "") {
                for (let i = 0; i < this.tempSkuForm.skuList.length; i++) {
                    if (this.tempSkuForm.skuList[i].id !== "guige") {
                        this.tempSkuForm.skuList[i].children = this.tempSkuForm.skuList[i].children.filter(f => f.name.includes(this.searchSkuName))
                    }
                }

            }

        },
        all() {
            for (let i = 0; i < this.tempSkuForm.skuList.length; i++) {
                if (this.tempSkuForm.skuList[i].id !== "guige") {
                    let size = this.tempSkuForm.skuList[i].children.length
                    let checkSize = this.tempSkuForm.skuList[i].checkIds.length
                    if (size === checkSize) {
                        this.tempSkuForm.skuList[i].checkIds = []
                    } else {
                        this.tempSkuForm.skuList[i].checkIds = []
                        this.tempSkuForm.skuList[i].children.forEach(f => this.tempSkuForm.skuList[i].checkIds.push(f.id))
                    }

                }
            }

        },
        removeSkuTable(list, index) {
            let ind = (this.currentPage - 1) * 15 + index
            list.splice(ind, 1);
        },
        addSkuAttr(data) {
            if (data.expand === null || data.expand === undefined || data.expand.length === 0) {
                return
            }
            console.log(this.examId)
            post("/exam/package/sku/attr/auto-add", {
                pid: data.id,
                value: data.expand,
                examId: this.dataForm.examId
            }).then(res => {
                data.children.push(res)
                this.skuAttrMap[res.id] = res
                data.expand = ""
            })
        },
        //根据科目获取产品
        getProductData(scopeData, refresh = true) {
            if (refresh) {
                scopeData.productIds = [];
            }
            scopeData.productList = [];
            if (scopeData.categoryIds && scopeData.categoryIds.length > 0) {
                scopeData.categoryIds.forEach(ca => {
                    this.productData.forEach(p => {
                        if (Number(ca) === Number(p.categoryId)) {
                            scopeData.productList.push(p);
                        }
                    })
                })
            }

        },
        createSku() {
            // this.test();
            let skuAttrObj = {};
            this.skuForm.skuAttrList = [];
            let checkList = [];
            this.tempSkuForm.skuList.forEach(e => {
                if (e.checkIds.length > 0) {
                    skuAttrObj[e.id] = e.checkIds;
                    checkList.push(e.checkIds)

                }
            })
            this.dataForm.skuAttrs = skuAttrObj;
            if (checkList.length > 0) {
                this.getSkuData([], 0, checkList);
                //生成sku
                this.createTable();
            } else {
                this.$message.warning("请先选择sku属性");
                // this.activeName = "third";
            }
        },
        getSkunames(skuIds) {
            if (!skuIds || skuIds.length < 1) {
                return [];
            }
            let nameList = [];
            skuIds.forEach(id => {
                nameList.push(this.skuAttrMap[id].name)
            })
            return nameList;
        },
        createTable() {
            this.submitFlag = true;
            this.newSkuTable = [];
            this.skuForm.skuAttrList.forEach(sku => {
                let tmpObj = {
                    ...this.skuObj
                };
                tmpObj.industryId = this.dataForm.industryId;
                tmpObj.examId = this.dataForm.examId;
                tmpObj.price = this.dataForm.price;
                tmpObj.discountPrice = this.dataForm.discountPrice;
                tmpObj.agentPrice = this.dataForm.agentPrice;
                tmpObj.tmPrice = this.dataForm.tmPrice;
                tmpObj.skuAttrIds = sku;
                tmpObj.skuAttrNameList = this.getSkunames(sku);
                tmpObj.categoryIds = [];
                tmpObj.skuAttrNameList.map((item, index) => {
                    if (item === "单科" || item === "全科") {
                        tmpObj.skuAttrNameList.unshift(tmpObj.skuAttrNameList.splice(index, 1)[0]);
                    }
                })
                tmpObj.name = tmpObj.skuAttrNameList.reverse().join("");
                this.getProductData(tmpObj);
                this.newSkuTable.push(tmpObj);
            });
            // if (this.skuForm.categoryIds.length > 0) {
            //     this.skuForm.skuAttrList.forEach(sku => {
            //
            //         if (sku.includes("quanKe")) {
            //             this.skuForm.categoryIds.forEach(categoryId => {
            //                 let tmpObj = {
            //                     ...this.skuObj
            //                 };
            //                 tmpObj.industryId = this.dataForm.industryId;
            //                 tmpObj.examId = this.dataForm.examId;
            //                 tmpObj.price = this.dataForm.price;
            //                 tmpObj.discountPrice = this.dataForm.discountPrice;
            //                 tmpObj.agentPrice = this.dataForm.agentPrice;
            //                 tmpObj.tmPrice = this.dataForm.tmPrice;
            //                 tmpObj.skuAttrIds = sku;
            //                 tmpObj.skuAttrNameList = this.getSkunames(sku);
            //                 tmpObj.categoryIds = [];
            //
            //                 if (!this.baseCategoryIds.includes(Number(categoryId))) {
            //                     tmpObj.name = this.categoryMap[categoryId].name;
            //                     tmpObj.categoryIds.push(categoryId);
            //                     this.baseCategoryIds.forEach(base => {
            //                         tmpObj.categoryIds.push(base);
            //                     })
            //                     this.getProductData(tmpObj);
            //                     this.newSkuTable.push(tmpObj);
            //                 }
            //
            //             })
            //         } else {
            //             this.skuForm.categoryIds.forEach(categoryId => {
            //                 let tmpObj = {
            //                     ...this.skuObj
            //                 };
            //                 tmpObj.industryId = this.dataForm.industryId;
            //                 tmpObj.examId = this.dataForm.examId;
            //                 tmpObj.price = this.dataForm.price;
            //                 tmpObj.discountPrice = this.dataForm.discountPrice;
            //                 tmpObj.agentPrice = this.dataForm.agentPrice;
            //                 tmpObj.tmPrice = this.dataForm.tmPrice;
            //                 tmpObj.skuAttrIds = sku;
            //                 tmpObj.skuAttrNameList = this.getSkunames(sku);
            //                 tmpObj.categoryIds = [];
            //                 tmpObj.name = this.categoryMap[categoryId].name;
            //                 tmpObj.categoryIds.push(categoryId);
            //                 this.getProductData(tmpObj);
            //                 this.newSkuTable.push(tmpObj);
            //
            //             })
            //         }
            //
            //     })
            //     this.activeName = "third";
            // } else {
            //     this.$message.warning("请选择科目");
            // }
            this.activeName = "third";
            this.submitFlag = false;
        },
        // test() {
        //     this.skuForm.skuAttrList = [];
        //     let checkArry = [["1", "2"], ["大", "小"], ["红", "黄", "蓝"]];
        //     if (checkArry.length > 0) {
        //         this.getSkuData([], 0, checkArry);
        //         console.log("skuAttrList:", this.skuForm.skuAttrList)
        //     } else {
        //         this.$message.warning("eeee");
        //     }
        //
        // },
        getSkuData(skuArr = [], i, list) {
            for (let j = 0; j < list[i].length; j++) {
                if (i < list.length - 1) {
                    skuArr[i] = list[i][j];
                    this.getSkuData(skuArr, i + 1, list);
                } else {
                    this.skuForm.skuAttrList.push([...skuArr, list[i][j]])
                }
            }

        },
        loadTags(examId) {
            get("/exam/package/tag/commonAndExamTags", {
                size: 1000,
                examId: examId
            }).then(res => {
                this.tagList = res;
            })
        },
        loadSku(examId) {
            this.skuForm.skuList = [];
            if (!examId) {
                return;
            }
            get("/exam/package/sku/attr/allEnableListTree", {
                examId,
                size: 1000,
            }).then(res => {
                let list = res || [];
                list = list.map(da => {
                    let checkIds = []
                    let childrenIds = []
                    da.children.forEach(child => {
                        this.skuAttrMap[child.id] = child;
                        childrenIds.push(child.id)
                    })
                    da.expand = ""
                    if (!this.addAction && this.firstupdateSkuAttr) {
                        if (this.dataForm.skuAttrs) {
                            let tmpCheckIds = this.dataForm.skuAttrs[da.id] || [];
                            tmpCheckIds.forEach(tmpId => {
                                if (childrenIds.includes(tmpId)) {
                                    checkIds.push(tmpId)
                                }
                            })
                        }

                    }


                    return {
                        ...da,
                        checkIds: checkIds,
                    };
                });
                this.firstupdateSkuAttr = false;
                this.skuForm.skuList = list;
                let stringify = JSON.stringify(list);
                this.tempSkuForm.skuList = JSON.parse(stringify);
            })
        },
        loadOldData(id) {
            if (id) {
                get(`/exam/package/detail/${id}`, {id: id}).then(res => {
                    res.price = res.price / 100;
                    res.discountPrice = res.discountPrice / 100;
                    res.agentPrice = res.agentPrice / 100;
                    res.tmPrice = res.tmPrice / 100;
                    res.introduce = res.introduce ||[];

                    beanCopy(res, this.dataForm);
                    // this.skuForm = res
                })
                // get("/exam/package/sku/list", {packageId: id, size: 1000, attr: true}).then(res => {
                //     this.tableData = res || [];
                //     this.tableData.forEach(data => {
                //         data = {
                //             ...data,
                //             productList: null
                //         }
                //         this.getProductData(data);
                //     })
                // })
            } else {
                this.dataForm = this.initAddForm;
            }
        },
        save() {
            this.canSave = true;
            let loading = this.$loading({
                lock: true,
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.3)"
            });
            let packageData = {
                ...this.dataForm
            }
            packageData.price = packageData.price * 100;
            packageData.discountPrice = packageData.discountPrice * 100;
            packageData.agentPrice = packageData.agentPrice * 100;
            packageData.tmPrice = packageData.tmPrice * 100;
            if (!packageData.endDate) {
                delete packageData.endDate;
            }
            delete packageData.createdTime;
            delete packageData.modifyTime;
            let skuData = [];
            this.tableData.forEach(sku => {
                if (!sku.productIds || sku.productIds.length === 0) {
                    this.canSave = false;
                    return;
                }
                let tmpSku = {
                    ...sku
                }
                tmpSku.price = tmpSku.price * 100;
                tmpSku.discountPrice = tmpSku.discountPrice * 100;
                tmpSku.agentPrice = tmpSku.agentPrice * 100;
                tmpSku.tmPrice = tmpSku.tmPrice * 100;
                delete tmpSku.createdTime;
                delete tmpSku.modifyTime;
                skuData.push(tmpSku);
            })
            if (!this.canSave) {
                this.$confirm("产品不能为空!")
                loading && loading.close();
                return
            }
            this.newSkuTable.forEach(sku => {
                if (!sku.productIds || sku.productIds.length === 0) {
                    this.canSave = false;
                    return;
                }
                let tmpSku = {
                    ...sku
                }
                tmpSku.price = tmpSku.price * 100;
                tmpSku.discountPrice = tmpSku.discountPrice * 100;
                tmpSku.agentPrice = tmpSku.agentPrice * 100;
                tmpSku.tmPrice = tmpSku.tmPrice * 100;
                skuData.push(tmpSku);
            })
            if (!this.canSave) {
                this.$confirm("产品不能为空!")
                loading && loading.close();
                return
            }
            post("exam/package/addOrUpdateAll", {
                packageStr: JSON.stringify(packageData),
                packageSkuStr: JSON.stringify(skuData)
            }).then(res => {
                this.$message.success("保存成功");
                this.closeTagThisAndBack("list?refresh=true");
            }).finally(() => {
                loading && loading.close();
            })
        },
        handleClick(tab, event) {
        },
        loadCategory(examId, name) {
            this.baseCategoryIds = [];
            this.categoryMap = {};
            this.categoryFlag = true;
            get("/exam/category/list", {
                examId,
                name,
                size: 2000,
                tree: false
            })
                .then(res => {
                    res.forEach(c => {
                        this.categoryMap[c.id] = c;
                        if (16 === (c.attribute & 16)) {
                            this.baseCategoryIds.push(Number(c.id));
                        }
                    })
                    this.categoryData = treeList2Tree(res);
                    // this.categoryData = res;
                })
                .finally(() => {
                    this.categoryFlag = false;
                });
        },
        loadProduct(examId, name) {
            this.productData = [];
            get("/exam/product/base/list", {
                examId,
                name,
                size: 3000,
            })
                .then(res => {
                    this.productData = res;
                    if (!this.addAction && this.loadSkuListFirst) {
                        get("/exam/package/sku/list", {
                            packageId: this.dataForm.id,
                            size: 10000,
                            attr: true
                        }).then(res => {
                            this.loadSkuListFirst = false;
                            this.tableData = res || [];
                            this.tableData.forEach(data => {
                                data.price = data.price / 100;
                                data.discountPrice = data.discountPrice / 100;
                                data.agentPrice = data.agentPrice / 100;
                                data.tmPrice = data.tmPrice / 100;
                                this.getProductData(data, false);
                            })
                            this.total = this.tableData.length
                        })
                        // this.getSkuAll(1);
                    }
                })
            ;
        },
        getSkuAll(page) {
            get("/exam/package/sku/page", {
                packageId: this.dataForm.id,
                page: page,
                attr: true
            }).then(res => {
                console.log(res)
                this.loadSkuListFirst = false;
                this.tableData = res.records || [];
                this.tableData.forEach(data => {
                    data.price = data.price / 100;
                    data.discountPrice = data.discountPrice / 100;
                    data.agentPrice = data.agentPrice / 100;
                    data.tmPrice = data.tmPrice / 100;
                    this.getProductData(data, false);
                })
                if (res.total / (page * 10) > 1) {
                    console.log(res.total, page)
                    this.getSkuAll(page + 1)

                }
            })
        },
        changePrice(attributes, data) {
            var number = data.skuAttrNameList.indexOf("全科");
            if (number > -1) {
                this.tableData.forEach(e => {
                    if (e.skuAttrNameList.indexOf("全科") > -1) {
                        e[attributes] = data[attributes]
                    }
                })
            } else if (data.skuAttrNameList.indexOf("单科") > -1) {
                this.tableData.forEach(e => {
                    if (e.skuAttrNameList.indexOf("单科") > -1) {
                        e[attributes] = data[attributes]
                    }
                })
            }
        },
        newChangePrice(attributes, data) {
            var number = data.skuAttrNameList.indexOf("全科");
            if (number > -1) {
                this.newSkuTable.forEach(e => {
                    if (e.skuAttrNameList.indexOf("全科") > -1) {
                        e[attributes] = data[attributes]
                    }
                })
            } else if (data.skuAttrNameList.indexOf("单科") > -1) {
                this.newSkuTable.forEach(e => {
                    if (e.skuAttrNameList.indexOf("单科") > -1) {
                        e[attributes] = data[attributes]
                    }
                })
            }

        },
        toSku() {
            this.$refs.dataForm.validate(valid => {
                if (valid) {
                    if ((!this.dataForm.days || 0 === this.dataForm.days) && !this.dataForm.endDate) {
                        this.$message.warning("有效天数(优先)和有效日期不能同时为空")
                        return;
                    }
                    this.activeName = "second";
                } else {
                    j();
                }
            });

        },
        loadExam(industryId, name) {
            this.examFlag = true;
            get("/exam/exam/list", {
                industryId,
                name,
                size: 1000
            })
                .then(res => {
                    this.examData = res;
                })
                .finally(() => {
                    this.examFlag = false;
                });
        },
        handleCurrentChange(val) {
            this.currentPage = val
        },
        loadIndustry() {
            this.industryFlag = true;
            get("/exam/industry/list", {size: 1000})
                .then(res => {
                    this.industryData = res;
                })
                .finally(() => {
                    this.industryFlag = false;
                });
        },
    }
};
</script>

<style lang="scss" scoped>
::v-deep .el-transfer-panel {
    width: 300px;
}

.el-table {
    width: 99.9% !important;
}

.formRow {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader ::v-deep .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
